import _ from 'lodash';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import Seo from '@/core/components/Seo';
import { getIdFromSlug, getNameFromSlug } from '@/core/utils/slug';
import Breadcrumb from '@/lib/category/components/Breadcrumb';
import { useEffect, useState } from 'react';
import odooApi from '@/core/api/odooApi';

const BasicLayout = dynamic(() => import('@/core/components/layouts/BasicLayout'));
const ProductSearch = dynamic(() => import('@/lib/product/components/ProductSearch'));
const CategorySection = dynamic(() => import('@/lib/product/components/CategorySection'));

export default function CategoryDetail() {
  const router = useRouter();
  const { slug = '', page = 1 } = router.query;
  const [dataLob, setDataLob] = useState([]);
  const [finalQuery, setFinalQuery] = useState({});
  
  const categoryName = getNameFromSlug(slug);
  const lobId = getIdFromSlug(slug);

  useEffect(() => {
    const fetchCategoryData = async () => {
      try {
        const lobData = await odooApi('GET', `/api/v1/lob_homepage?lob_id=${lobId}`);
        setDataLob(lobData);
      } catch (error) {
        console.error("Error fetching category data:", error);
      }
    };

    fetchCategoryData();
  }, [lobId]);

  console.log("dataLob",dataLob)
  
  useEffect(() => {
      const collectIds = (categories) => {
          return categories?.categoryIds?.map(data => data.id) || [];
        };
        
        const ids = collectIds(dataLob[0]);
        const newQuery = {
            fq: `category_id_ids:(${ids.join(' OR ')})`,
            page: 1,
            brand: router.query.brand || '',
        };
        setFinalQuery(newQuery);
        console.log("finalQuery",finalQuery)
  }, [dataLob, router.query.brand]);

  return (
    <BasicLayout>
      <Seo
        title={`Beli ${categoryName} di Indoteknik`}
        description={`Jual ${categoryName} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar Balikpapan Medan Palembang Lampung Bali Bandung Makassar Manado.`}
        additionalMetaTags={[
          {
            property: 'keywords',
            content: `Jual ${categoryName}, harga ${categoryName}, ${categoryName} murah, toko ${categoryName}, ${categoryName} jakarta, ${categoryName} surabaya`,
          },
        ]}
      />

      <Breadcrumb categoryId={getIdFromSlug(slug)} />

      {!_.isEmpty(router.query) && (
        <ProductSearch query={finalQuery} categories={getIdFromSlug(slug)} prefixUrl={`/shop/lob/${slug}`} />
      )}
    </BasicLayout>
  );
}
